//1.导入vue 和 vuerouter 的包
import Vue from 'vue'
import VueRouter from 'vue-router'
import LayoutView from '@/pages/layout/LayoutView'
import LoginView from '@/pages/login/LoginView.vue'
// import Store from '@/store/index.js'

const Destination = () => import('@/pages/destination/Index.vue')
const Travel = () => import('@/pages/travel/Travel.vue')
const Community = () => import('@/pages/community/Community.vue')

const routerPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  const result = routerPush.call(this, location)
  return result ? result.catch(err => err) : Promise.resolve()
}

//2.调用vue.use() 函数，把 VueRouter 安装为 Vue 的插件
//vue.use()函数的作用，就是来安装插件的
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: LayoutView,
    children: [
      {
        path: '/',
        name: 'layout',
        component: () => import('@/pages/home/HomeView')
      },
      {
        path: '/dest',
        component: Destination,
        meta: {
          isLogin: true
        }
      },
      {
        path: '/travel',
        component: Travel,
        meta: {
          isLogin: true
        }
      },
      {
        path: '/community',
        component: Community,
        meta: {
          isLogin: true
        }
      },
      {
        path: '/about',
        name: 'about',
        component: () => import('@/pages/about/AboutView')
      }
    ]
  },
  {
    path: '/login',
    name: 'login',
    component: LoginView,
  }
]

//3.创建路由的实例对象
const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

//配置导航守卫
import store from '@/store'

// 配置导航守卫
router.beforeEach((to, from, next) => {
  if (to.meta.isLogin) {
    const isLogin = store.state.user.userInfo.isLogin
    if (isLogin) {
      next()
    } else {
      // ✅ 使用 setRedirectPath 修改 Vuex 中的 redirectPath
      store.commit('user/setRedirectPath', to.path)
      next('/login')
    }
  } else {
    next()
  }
})

//4.向外共享路由的实例对象
export default router